package group.ocr.Utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import java.util.UUID;
@Component
public class OSSUtils {
    private String endpoint="https://oss-cn-hangzhou.aliyuncs.com";
    private String accessKeyId="LTAI5tC916ALWph43UdStsEe";
    private String accessKeySecret="h6NcSUmeo8jPY1bZKBV0HaTRPOncrA";
    private String bucketName="hy-ocr-program";
    //上传文件到阿里云
    public String upload(MultipartFile file) throws IOException {
        // 获取上传文件的输入流
        InputStream inputStream = file.getInputStream();
        // 避免文件覆盖，生成新的文件名
        String originalFilename = file.getOriginalFilename();
        String fileName = null;
        if (originalFilename != null) {
            fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        // 创建OSSClient对象
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 上传文件到OSS
        ossClient.putObject(bucketName, fileName, inputStream);
        // 设置授权的有效期为3600秒（1小时）
        long expiration = System.currentTimeMillis() + 3600L * 1000000;  // 当前时间+3600秒
        Date expirationDate = new Date(expiration);
        // 生成一个URL，允许访问刚刚上传的文件，并设置URL过期时间
        GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, fileName);
        generatePresignedUrlRequest.setExpiration(expirationDate);
        // 获取临时URL
        URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest);
        // 关闭OSSClient
        ossClient.shutdown();
        // 返回临时授权URL
        return url.toString();
    }
}
